package IO流.课后作业.M4;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static List<Staff> list=new ArrayList<>();
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        String path="E://Staff.txt";
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(path));

        Staff s=new Staff("张三",28,5600);
        Staff staff=new Staff("李四",39,6500);
        list.add(s);
        list.add(staff);
        oos.writeObject(list);
        oos.close();

        list.clear();
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream(path));
        list= (ArrayList<Staff>) ois.readObject();
        for (Staff st : list) {
            System.out.println("姓名："+st.getName());
            System.out.println("年龄"+st.getAge());
            System.out.println("月薪"+st.getSalary());
            System.out.println("-----------------------");
        }
        System.out.println("\n========================================");
        staff=new Staff("Tom",30,5000);
        saveStaffToFile(staff, new File(path));

        for (Staff st : list) {
            System.out.println("姓名："+st.getName());
            System.out.println("年龄"+st.getAge());
            System.out.println("月薪"+st.getSalary());
            System.out.println("-----------------------");
        }
        File file=new File("java.io/work/test.txt");
        List list=readStaffFromFile(file);
        for (Object sa : list) {
            System.out.println(sa);
        }
    }

    /**
     * 4） 写一个方法List<Staff> readStaffFromFile(File file)，该方法读某
     *  * 个文件，从文件信息中创建一个Staff 类型的List。
     *  * 例如，假设文件内容如下：
     *  * Tom/30/5000
     *  * Jim/25/3000
     *  * Terry/33/4500
     *  * 则返回一个包含三个Staff 对象的List。
     * @param file
     * @return
     */
    public static List<Staff> readStaffFromFile(File file)throws IOException{
        BufferedReader br=new BufferedReader(new FileReader(file.getAbsoluteFile()));
        String line=null;
        String[]str=null;
        List list=new ArrayList();
        while ((line=br.readLine())!=null){
            str= line.split("/",3);
            Staff staff=new Staff(str[0],Integer.parseInt(str[1]),Integer.parseInt(str[2]));
            list.add(staff);
        }
        return list;
    }
    public static void saveStaffToFile(Staff staff, File file) throws IOException {
        list.add(staff);
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(file,true));
        oos.writeObject(list);
        BufferedWriter bw=new BufferedWriter(new FileWriter(file,true));
        bw.newLine();
        bw.write("Tom/30/5000");
        bw.close();
        oos.close();
    }
}
